// ajax请求
function ajax(options) {
    return wx.request({
        url: options.url,
        method: options.method || 'get',
        data: options.data,
        header: options.header || {
            "Content-Type": "application/x-www-form-urlencoded"
        },
        success: function(res) {
            options.callback && options.callback(null, res)
        },
        fail: function(error) {
            options.callback && options.callback(error)
        }
    });
}

function getDate(day) {
    var date = new Date();
    date.setDate(date.getDate() + day);
    var y = date.getFullYear();
    var m = date.getMonth() + 1;
    var d = date.getDate();
    return [y, m, d].map(formatNumber).join('-');
}

function getMonth(month) {
    var date = new Date();
    date.setMonth(date.getMonth() + month);
    var y = date.getFullYear();
    var m = date.getMonth() + 1;
    return [y, m].map(formatNumber).join('-');
}

function getYear(year) {
    var date = new Date();
    var y = date.getFullYear() + year;
    return y + '';
}

function timeDifference(date1, date2) {
    var date1 = new Date(date1);
    var date2 = new Date(date2);
    var newYear = date1.getFullYear();
    var newMonth = date1.getMonth() + 12;
    console.log(newMonth)
    if (newMonth >= 11) {
        newYear += 1;
        newMonth -= 11;
        date1.setFullYear(newYear);
        date1.setMonth(newMonth - 1);
    } else {
        date1.setFullYear(newYear);
        date1.setMonth(newMonth);
    }
    if (date1.getTime() >= date2.getTime()) {
        return false;
    } else {
        return true;
    }
}
// 验证邮箱合法性
function validatorEmail(email) {
    return /^[a-z0-9]+([\._\\-]*[a-z0-9])*@([a-z0-9]+[-a-z0-9]*[a-z0-9]+\.){1,63}[a-z0-9]+$/.test(
        email
    );
}

// 验证手机号码合法性
function validatorPhone(phone) {
    return /^(1[3|5|7|8][0-9]|14[5|7]|15[0|1|2|3|5|6|7|8|9]|18[0|1|2|3|5|6|7|8|9]|19[8|9]|166)\d{8}$/.test(
        phone
    );
}

// 验证密码合法性
function validatorPassword(pwd) {
    // return /^[\w!@#$%^&*\.]{6,16}$/.test(pwd);
    return /^[\w|\d]{6,20}$/.test(pwd);
}

const formatTime = date => {
    const year = date.getFullYear()
    const month = date.getMonth() + 1
    const day = date.getDate()
    const hour = date.getHours()
    const minute = date.getMinutes()
    const second = date.getSeconds()

    return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}

const formatNumber = n => {
    n = n.toString()
    return n[1] ? n : '0' + n
}

module.exports = {
    ajax,
    formatTime,
    timeDifference,
    getYear,
    getMonth,
    getDate,
    validatorEmail,
    validatorPhone,
    validatorPassword
}